﻿using System;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections.Generic;

using System.IO;
using Microsoft.International.Converters.PinYinConverter;
using System.Threading;


namespace Gtkj.CMS.Common
{
    /// <summary>
    /// 字符串帮助类
    /// </summary>
    public class StringHelper
    {

        /// <summary>
        /// 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数
        /// </summary>
        /// <returns></returns>
        public static string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        /// <summary>
        /// 生成随机串，随机串包含字母或数字
        /// </summary>
        /// <returns></returns>
        public static string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

        /// <summary>
        /// 防止创建类的实例
        /// </summary>
        private StringHelper() { }

        /// <summary>
        /// 去除字符串末尾的结束符\0
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SubStringEnd(string str)
        {
            int index;
            while ((index = str.LastIndexOf("\0")) != -1)
            {
                if (index != str.Length - 1)
                    break;
                str = str.Substring(0, index);
            }
            return str;
        }

        private static readonly object Locker = new object();
        private static int _sn = 0;

        /// <summary>
        /// 不重复编号
        /// </summary>
        /// <returns></returns>
        public static string GenerateId()
        {
            lock (Locker)  //lock 关键字可确保当一个线程位于代码的临界区时，另一个线程不会进入该临界区。
            {
                if (_sn == 999)
                {
                    _sn = 0;
                }
                else
                {
                    _sn++;
                }

                Thread.Sleep(100);

                return DateTime.Now.ToString("yyyyMMddHHmmss") + _sn.ToString().PadLeft(3, '0');
            }
        }


        /// <summary>
        /// 生成用户编号
        /// </summary>
        /// <returns></returns>
        public static string GenerateUserId()
        {
            lock (Locker)  //lock 关键字可确保当一个线程位于代码的临界区时，另一个线程不会进入该临界区。
            {
                if (_sn == 9)
                {
                    _sn = 0;
                }
                else
                {
                    _sn++;
                }

                Thread.Sleep(100);

                return DateTime.Now.ToString("yyyyMMddHHmmss") + _sn.ToString().PadLeft(3, '0');
            }
        }

        /// 获得字符串中开始和结束字符串中间得值 
        /// </summary> 
        /// <param name="str"></param> 
        /// <param name="s">开始</param> 
        /// <param name="e">结束</param> 
        /// <returns></returns> 
        public static string getvalue(string str, string start, string end)
        {
            Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);

            return rg.Match(str).Value;
        }

        /// <summary>
        /// 返回指定位数的随机数字符串
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GetRandomNumCode(int len)
        {
            Random r = new Random();
            string code = null;
            for (int i = 0; i < len; i++)
            {
                code += r.Next(0, 10);
            }
            return code;
        }
        /// <summary>
        /// 获得字符串的长度,一个汉字的长度为1
        /// </summary>
        public static int GetStringLength(string s)
        {
            if (!string.IsNullOrEmpty(s))
                return Encoding.Default.GetBytes(s).Length;

            return 0;
        }

        /// <summary>
        /// 获得字符串中指定字符的个数
        /// </summary>
        /// <param name="s">字符串</param>
        /// <param name="c">字符</param>
        /// <returns></returns>
        public static int GetCharCount(string s, char c)
        {
            if (s == null || s.Length == 0)
                return 0;
            int count = 0;
            foreach (char a in s)
            {
                if (a == c)
                    count++;
            }
            return count;
        }

        /// <summary>
        /// 获得指定顺序的字符在字符串中的位置索引
        /// </summary>
        /// <param name="s">字符串</param>
        /// <param name="order">顺序</param>
        /// <returns></returns>
        public static int IndexOf(string s, int order)
        {
            return IndexOf(s, '-', order);
        }

        /// <summary>
        /// 获得指定顺序的字符在字符串中的位置索引
        /// </summary>
        /// <param name="s">字符串</param>
        /// <param name="c">字符</param>
        /// <param name="order">顺序</param>
        /// <returns></returns>
        public static int IndexOf(string s, char c, int order)
        {
            int length = s.Length;
            for (int i = 0; i < length; i++)
            {
                if (c == s[i])
                {
                    if (order == 1)
                        return i;
                    order--;
                }
            }
            return -1;
        }

        #region 分割字符串

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="splitStr">分隔字符串</param>
        /// <returns></returns>
        public static string[] SplitString(string sourceStr, string splitStr)
        {
            if (string.IsNullOrEmpty(sourceStr) || string.IsNullOrEmpty(splitStr))
                return new string[0] { };

            if (sourceStr.IndexOf(splitStr) == -1)
                return new string[] { sourceStr };

            if (splitStr.Length == 1)
                return sourceStr.Split(splitStr[0]);
            else
                return Regex.Split(sourceStr, Regex.Escape(splitStr), RegexOptions.IgnoreCase);

        }

        /// <summary>
        /// 分割字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <returns></returns>
        public static string[] SplitString(string sourceStr)
        {
            return SplitString(sourceStr, ",");
        }

        #endregion

        #region 截取字符串

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="startIndex">开始位置的索引</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns></returns>
        public static string SubString(string sourceStr, int startIndex, int length)
        {
            if (!string.IsNullOrEmpty(sourceStr))
            {
                if (sourceStr.Length >= (startIndex + length))
                    return sourceStr.Substring(startIndex, length);
                else
                    return sourceStr.Substring(startIndex);
            }

            return "";
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns></returns>
        public static string SubString(string sourceStr, int length)
        {
            return SubString(sourceStr, 0, length);
        }

        #endregion

        #region 移除前导/后导字符串

        /// <summary>
        /// 移除前导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <returns></returns>
        public static string TrimStart(string sourceStr, string trimStr)
        {
            return TrimStart(sourceStr, trimStr, true);
        }

        /// <summary>
        /// 移除前导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static string TrimStart(string sourceStr, string trimStr, bool ignoreCase)
        {
            if (string.IsNullOrEmpty(sourceStr))
                return string.Empty;

            if (string.IsNullOrEmpty(trimStr) || !sourceStr.StartsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
                return sourceStr;

            return sourceStr.Remove(0, trimStr.Length);
        }

        /// <summary>
        /// 移除后导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <returns></returns>
        public static string TrimEnd(string sourceStr, string trimStr)
        {
            return TrimEnd(sourceStr, trimStr, true);
        }

        /// <summary>
        /// 移除后导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static string TrimEnd(string sourceStr, string trimStr, bool ignoreCase)
        {
            if (string.IsNullOrEmpty(sourceStr))
                return string.Empty;

            if (string.IsNullOrEmpty(trimStr) || !sourceStr.EndsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
                return sourceStr;

            return sourceStr.Substring(0, sourceStr.Length - trimStr.Length);
        }

        /// <summary>
        /// 移除前导和后导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <returns></returns>
        public static string Trim(string sourceStr, string trimStr)
        {
            return Trim(sourceStr, trimStr, true);
        }

        /// <summary>
        /// 移除前导和后导字符串
        /// </summary>
        /// <param name="sourceStr">源字符串</param>
        /// <param name="trimStr">移除字符串</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static string Trim(string sourceStr, string trimStr, bool ignoreCase)
        {
            if (string.IsNullOrEmpty(sourceStr))
                return string.Empty;

            if (string.IsNullOrEmpty(trimStr))
                return sourceStr;

            if (sourceStr.StartsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
                sourceStr = sourceStr.Remove(0, trimStr.Length);

            if (sourceStr.EndsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
                sourceStr = sourceStr.Substring(0, sourceStr.Length - trimStr.Length);

            return sourceStr;
        }

        #endregion

        /// <summary>
        /// 元素数据转INT列表
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static List<int> ElementToIntList(string str)
        {
            if(String.IsNullOrEmpty(str))
            {
                return null;
            }
            List<int> list = new List<int>();
            if (str.IndexOf(",") == -1)
            {
                list = new List<int>() { int.Parse(str) };
            }
            else
            {
                List<string> strList = new List<string>(str.Split(new[] { ',' }));
                foreach (var item in strList)
                {
                    list.Add(Convert.ToInt32(item));
                }

            }
            return list;
        }

        /// <summary>
        /// 如果源字符串为空，返回默认值，如果不为空，转为数字后返回结果
        /// </summary>
        /// <param name="str"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static int IsNull(string str,int def)
        {
            if(string.IsNullOrEmpty(str))
            {
                return def;
            }
            return int.Parse(str);
        }
        /// <summary>
        /// 如果字符串为空，返回默认值，如果不为空，直接返回源字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static string IsNull(string str, string def)
        {
            if (string.IsNullOrEmpty(str))
            {
                return def;
            }
            return str;
        }

        //#region 创建订单编号
        ///// <summary>
        ///// 创建订单编号
        ///// </summary>
        ///// <returns>订单编号</returns>
        //public static string CreateOrderNum()
        //{
        //    DateTime t_currentdate = DateTime.Now;

        //    string t_ordernum = t_currentdate.ToString(CommonInfo.m_AllTimeFormat);
        //    t_ordernum = t_ordernum + CreateRandom(CommonInfo.m_RandomCodeLength);

        //    return t_ordernum;
        //}
        //#endregion


        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="Text">需要截取的字符串</param>
        /// <param name="start">开始位置</param>
        /// <param name="length">截取的长度</param>
        /// <param name="last">补充的字符串   (...)</param>
        /// <returns></returns>
        public static string subStr(string Text, int start, int length, string last)
        {
            if (Text.Length > length)
            {
                return Text.Substring(start, length) + last;
            }
            else
            {
                return Text;
            }
        }
        #region 生成随机数
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="o_length">随机数长度</param>
        /// <returns>随机数</returns>
        public static string CreateRandom(int o_length)
        {
            string[] t_srandomcode = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            Random o_random = new Random();
            StringBuilder o_stringbuilder = new StringBuilder();

            int t_irandomcodelength = t_srandomcode.Length;

            for (int temp_ii = 0; temp_ii < o_length; temp_ii++)
            {
                o_stringbuilder.Append(t_srandomcode[o_random.Next(t_irandomcodelength - 1)]);
            }

            return o_stringbuilder.ToString();
        }
        #endregion

        #region 验证密码安全度
        public static int PasswordStrength(string password)
        {
            //空字符串强度值为0
            if (password == "") return 0;

            //字符统计
            int iNum = 0, iLtt = 0, iSym = 0;
            foreach (char c in password)
            {
                if (c >= '0' && c <= '9') iNum++;
                else if (c >= 'a' && c <= 'z') iLtt++;
                else if (c >= 'A' && c <= 'Z') iLtt++;
                else iSym++;
            }

            if (iLtt == 0 && iSym == 0) return 1; //纯数字密码
            if (iNum == 0 && iLtt == 0) return 1; //纯符号密码
            if (iNum == 0 && iSym == 0) return 1; //纯字母密码

            if (password.Length <= 6) return 1;   //长度不大于6的密码

            if (iLtt == 0) return 2; //数字和符号构成的密码
            if (iSym == 0) return 2; //数字和字母构成的密码
            if (iNum == 0) return 2; //字母和符号构成的密码

            //if (password.Length <= 10) return 2; //长度不大于10的密码

            return 3; //由数字、字母、符号构成的密码
        }
        #endregion

        #region 生成订单编号
        /// <summary>
        /// 生成订单编号(格式当前时间+6位随机数)
        /// </summary>
        /// <returns>订单编号</returns>
        public static string CreateOrderNum()
        {
            string t_ordernum = string.Empty;

            t_ordernum = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            t_ordernum = t_ordernum + CreateRandom(6);

            return t_ordernum;
        }
        #endregion

        #region 生成拼音码
        /// <summary>
        /// 生成拼音码
        /// </summary>
        /// <param name="name">输入的字符串</param>
        /// <param name="upper">返回大小写标志 true--大写 false--小写</param>
        /// <param name="space">间隔符</param>
        /// <param name="first">1--返回每个汉字的首拼</param>
        /// <param name="containError">是否容错，true--容错 false--直接返回空字符串</param>
        /// <returns>返回结果</returns>
        public static string TranToPinYin(string name, bool upper, string space, int first, bool containError)
        {
            string str = "";
            for (int i = 0; i < name.Length; i++)
            {
                if (ChineseChar.IsValidChar(name[i]))//判断是否是汉字
                {
                    ChineseChar cc = new ChineseChar(name[i]);
                    string temp = cc.Pinyins[0].Trim('1', '2', '3', '4', '5').ToString() + space;
                    if (upper)
                    {
                        temp = temp.ToUpper();
                    }
                    else
                    {
                        temp = temp.ToLower();
                    }
                    if (first == 1)
                    {
                        temp = temp.Substring(0, 1);
                    }
                    str += temp;//获取拼音，切掉空格,末尾加空格
                }
                else
                {
                    if (containError)
                    {
                        str += name[i];
                        continue;
                    }
                    else
                    {
                        return str = "";
                    }
                }
            }
            return str;
        }
        #endregion
    }
}